package com.ruoyi.web.controller.tool;


import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;

/**
 * nettyClient客户端
 *
 * @author Hack2003
 * @date 2024/3/13 17:24
 **/
public class NettyEchoClient {

    /**
     * Bootstrap：启动客户端和服务端程序的核心类。
     * EventLoopGroup：处理网络事件的线程池。
     * Channel：代表连接抽象。
     * ChannelFuture：表示异步操作结果。
     * ChannelPipeline：用于添加和处理Channel中的入站/出站事件处理器（Handler）。
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new StringDecoder(CharsetUtil.UTF_8));
                            ch.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8));
                            ch.pipeline().addLast(new EchoClientHandler());
                        }
                    });
            ChannelFuture f = b.connect(new InetSocketAddress("localhost", 8080)).sync();

            // 发送一条消息，并等待回应
            f.channel().writeAndFlush("Hello, World!").sync();

            // 关闭连接
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }

    public static class EchoClientHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) {
            System.out.println("Client received: " + msg); // 输出接收到的消息
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            cause.printStackTrace();
            ctx.close();
        }
    }
}